package org.example.system.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.ObjectUtils;
import org.example.system.common.exception.BusinessException;

import org.example.system.mapper.BizOrderMapper;
import org.example.system.model.entity.BizOrder;
import org.example.system.service.BizOrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;


@Service
public class BizOrderServiceImpl extends ServiceImpl<BizOrderMapper, BizOrder>
        implements BizOrderService {

    @Resource
    private BizOrderMapper orderMapper;

    /**
     * 根据订单号查询订单信息
     * @param orderSn 订单号
     * @return
     */
    @Transactional(readOnly = true,
            propagation = Propagation.SUPPORTS,
            rollbackFor = {
                    BusinessException.class,
                    Exception.class,
                    RuntimeException.class})
    @Override
    public BizOrder getOrderByOrderSn(String orderSn) {
        LambdaQueryWrapper<BizOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BizOrder::getOutTradeNo, orderSn);
        BizOrder order = orderMapper.selectOne(queryWrapper);
        if (ObjectUtils.isNotEmpty(order)) {
            return order;
        }
        return null;
    }

    /**
     * 更新订单状态
     *
     * @param orderSn 订单号
     * @param status  订单状态
     */
    @Transactional(
            rollbackFor = {Exception.class}
    )
    @Override
    public void updateOrderState(String orderSn, Integer status) {
        LambdaQueryWrapper<BizOrder> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(BizOrder::getOutTradeNo, orderSn);
        BizOrder order = orderMapper.selectOne(queryWrapper);
        if (order == null) {
            throw new BusinessException("此订单不存在");
        }
        order.setStatus(status);
        order.setUpdateTime(LocalDateTime.now());
        orderMapper.updateById(order);
    }

    // 创建 Snowflake 实例
    private final Snowflake snowflake = IdUtil.getSnowflake(1, 1);
    /**
     * 生成唯一编号
     *
     * @return 唯一编号（long类型）
     */
    @Override
    public String generateId() {
        return snowflake.nextIdStr();
    }
}




